import { useState } from "react";
import Render from "../../components/Render";
import { RoomType } from "../../components/Room";
import Chat from "../Chat";
import dayjs from "dayjs";
import { MessageType } from "../../components/Message";

export default function Crowd({room}: {
    room: RoomType,
}) {
    const [open, setOpen] = useState(false);
    const message: MessageType | undefined = [...room.messages].pop();

    return <>
        <div className="flex gap-4 w-full p-4 bg-white" onClick={() => setOpen(true)}>
            <div className="relative rounded h-[56px] w-[56px] bg-gray-200 p-[2px] flex flex-wrap items-center gap-[2px]">
                {
                    (room.members || []).slice(0, 9).map(
                        (member, index) => <img key={index} src={member.avatar} alt="user avatar" className="w-[16px] h-[16px] rounded-sm" />
                    )
                }
                {
                    room?.unread
                        ? <div className="absolute px-2 -top-2 -right-2 rounded-full bg-red-500 text-white text-sm">{room.unread}</div>
                        : <></>
                }
            </div>
            <div className="flex flex-col gap-2 text-gray-400 text-sm flex-1">
                <div className="flex justify-between items-center">
                    <div className="text-base font-medium text-black">{room.name}</div>
                    {
                        message
                            ? (
                                dayjs(message.createdAt).format('YYYYMMDD') >= dayjs().format('YYYYMMDD')
                                    ? <Render.Time className='text-xs' value={message.createdAt} />
                                    : <Render.Date className='text-xs' value={message.createdAt} />
                            )
                            : <></>
                    }
                </div>
                <div className="line-clamp-1">{message?.content}</div>
            </div>
        </div>

        <Chat open={open} onClose={() => setOpen(false)} title={room.name} room={room} />
    </>;
}